import axios from 'axios'
import store from '@/store/index.js'
import jsonBigint from 'json-bigint'
// 标准写法
const request = axios.create({
  baseURL: 'http://toutiao-app.itheima.net/',
  // 对返回的数据做处理
  // (1)无论服务器返回的状态值是否正常或者报错都会执行
  // (2)transformResponse 优先于 request.interceptors.response.use
  // (3)transformResponse处理最原始的数据(字符串),然后交给拦截器对对象做操作
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
    try {
      // return JSON.parse(data)
      return jsonBigint.parse(data)
    } catch (e) {
      // console.log(e)
      return data
    }
    // return data
  }]
})
// 对返回的数据做处理
request.interceptors.response.use(response => {
  // Do something before response is sent
  return response
}, error => {
// Do something with response error
  return Promise.reject(error)
})
request.interceptors.request.use(config => {
  if (store.state.user && store.state.user.token) {
    config.headers = {
      Authorization: `Bearer ${store.state.user.token}`
    }
  }
  // Do something before request is sent
  return config
}, error => {
// Do something with request error
  return Promise.reject(error)
})
export default request
